import {Button, Form, InputNumber, message, Modal, Select, Space} from "antd";
import React, {useEffect, useState} from "react";
import {useModel} from "@@/exports";
import {ActionType} from "@ant-design/pro-components";
import {addMonthlyPlanningNumberUsingPOST} from "@/services/model/monthlyPlanningController";
import {listProductionLineUsingGET} from "@/services/model/productionLineController";
import CustomSelect from "@/pages/components/CustomSelect";
import {mode} from "@antv/l7-utils/es/statistics";
const { Option } = Select;
type ModelProps = {
  isModalOpen: boolean,
  onCancel: () => void,
  actionRef: React.MutableRefObject<ActionType | undefined>,
}

const layoutStyle = {
  labelCol: {span: 6},
  wrapperCol: {span: 16},
};
const tailLayout = {
  wrapperCol: {offset: 8, span: 16},
};

const AddModel: React.FC<ModelProps> = ({
                                          isModalOpen,
                                          onCancel,
                                          actionRef
                                        }) => {
  const [addForm] = Form.useForm();

  const [prevItems, setPrevItems] = useState(isModalOpen);
  const [productionLineList, setProductionLineList] = useState<readonly API.ProductionLineDTO[]>([]);
  const [selectValue, setSelectValue] = useState('');
  if (isModalOpen !== prevItems) {
    setPrevItems(isModalOpen);
  }

  const {initialState} = useModel('@@initialState');
  useEffect(() => {
    listProductionLineUsingGET({
      commitUserId: initialState?.currentUser?.id,
    }).then((result) => {
      if (result.code === 0 && result.data) {
        setProductionLineList(result.data);
      }
    });
  }, []);
  useEffect(() => {
    addForm.resetFields();
    setSelectValue('')
  }, [isModalOpen]);
  const CodeList = () => {
    return (
      <CustomSelect name={"产线编码"}
                    selectDate={selectValue}
                    setSelectData={setSelectValue}
                    datalist={productionLineList.map(item => {
                      return {id: item.code, name: item.code}
                    })}/>
    );
  };

  const onSave = async (record: API.MonthlyPlanningNumberDTO) => {
    const currentUserId = initialState?.currentUser?.id;
    if (!(selectValue && record.planningNumber && record.year && record.month)) {
      message.warning("数据填写不完整")
      actionRef.current?.reload();
      return;
    }
    const newMonthlyPlanningNumber: API.AddMonthlyPlanningNumberQuery = {
      productionLineCode: selectValue,
      planningNumber: record.planningNumber,
      year: record.year,
      month: record.month,
      currentUserId,
    };
    const result = await addMonthlyPlanningNumberUsingPOST(newMonthlyPlanningNumber);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
    } else {
      message.error(result.message);
    }
    actionRef.current?.reload();
  };
  const onReset = () => {
    addForm.setFieldsValue({
      year: new Date().getFullYear(),
    })
    setSelectValue('')
    addForm.resetFields();
  };
  return (
    <>
      <Modal title={'新增 月度规划信息'} open={isModalOpen}
             onCancel={onCancel}
             footer={false}>
        <Form
          name="basic"
          form={addForm}
          {...layoutStyle}
          style={{maxWidth: 500}}
          onFinish={onSave}
        >
          <Form.Item
            label="产线编码"
            key='productionLineCode'
            name='productionLineCode'
            rules={[{required: true, message: '产线编码必填'}]}
          >
            <Select
              popupMatchSelectWidth={200}
              allowClear
              showSearch
              optionFilterProp="children"
              placeholder={'产线编码'}
              onClick={(e) => e.stopPropagation()}
              onChange={setSelectValue}
              value={selectValue}
            >
              {productionLineList.map(item => {
                return {id: item.code, name: item.code}
              }).map((item) => {
                  return (
                    <Option>
                      {item.name}
                    </Option>
                  );
                })}
            </Select>
          </Form.Item>
          <Form.Item
            label="年"
            key='year'
            name='year'
            rules={[{required: true, message: '年份必填'}, () => ({
              validator(_, value) {
                if (value && value < new Date().getFullYear()) {
                  return Promise.reject(new Error('年份必须大于等于本年'));
                }
                return Promise.resolve();
              },
            }),]}
          >
            <InputNumber placeholder={'年'}/>
          </Form.Item>
          <Form.Item
            label="月"
            key='month'
            name='month'
            rules={[{required: true, message: '月份必填'}, () => ({
              validator(_, value: number) {
                if (value !== undefined && (value > 12 || value < 1)) {
                  return Promise.reject(new Error('月份（1~12）'));
                }
                return Promise.resolve();
              },
            }),]}
          >
            <InputNumber placeholder={'月'}/>
          </Form.Item>
          <Form.Item
            label="产线规划人数"
            key='planningNumber'
            name='planningNumber'
            rules={[{required: true, message: '产线规划人数必填'}, () => ({
              validator(_, value: number) {
                if (value && value < 0) {
                  return Promise.reject(new Error('产线规划人数大于0'));
                }
                return Promise.resolve();
              },
            }),]}
          >
            <InputNumber placeholder={'数量'}/>
          </Form.Item>

          <Form.Item {...tailLayout} key="submit&reset">
            <Space>
              <Button type="primary" htmlType="submit" key="submit">
                提交
              </Button>
              <Button htmlType="button" onClick={onReset} key="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddModel;



